/**
 * 通用js
 */

//上传文件
function uploadImage(param, callBack) {

  // 覆盖初始化参数
  var sizeType = param.sizeType ? param.sizeType : ['compressed'];
  var sourceType = param.sourceType ? param.sourceType : ['album', 'camera'];
  var count = param.count ? param.count : 1;
  //文件上传地址
  var uploadUrl = param.uploadUrl ? param.uploadUrl : '/wxapi/uploadFile/doUpload';
  uploadUrl = getApp().baseUrl + uploadUrl;
  //默认传参
  var formData = param.uploadUrl ? param.uploadUrl : {};

  //选择照片
  wx.chooseImage({
    count: count,
    sizeType: sizeType,
    sourceType: sourceType,
    success: function(res) {
      //开始上传
      var tempFilePaths = res.tempFilePaths
      wx.showToast({
          icon: "loading",
          title: "正在上传"
        }),
        wx.getStorage({
          key: 'token',
          success: function(res) {
            for (var i = 0; i < tempFilePaths.length; i++) {
              wx.uploadFile({
                url: uploadUrl,
                filePath: tempFilePaths[i],
                name: 'file',
                header: {
                  "Content-Type": "multipart/form-data",
                  'token': res.data
                },
                formData: formData,
                success: function(e) {
                  console.log("上传完成", e);

                  if (e.statusCode != 200) {
                    wx.showModal({
                      title: '提示',
                      content: '上传失败',
                      showCancel: false
                    })
                    return;
                  }

                  var data = JSON.parse(e.data) //上传返回值

                  if (data.status == '200') {
                    var url = data.mapInfo.url
                    console.log("上传成功的图片路径：" + url);
                    callBack(data);
                  }
                },
                fail: function(e) {
                  console.log(e);
                  wx.showModal({
                    title: '提示',
                    content: '上传失败',
                    showCancel: false
                  })
                },
                complete: function() {
                  wx.hideToast(); //隐藏Toast
                }
              })
            }

          }
        })
    }
  })


}


/**
 * 表单验证
 * 满足验证要求返回true，否者返回false
 */
function validForm(formData, rules) {
  //验证结果记录
  var result = true;
  //定义一些默认的规则
  var def_rules = {
    //手机号码
    "$tel": {
      "rule": /(^([0-9]{3,4}-)?[0-9]{7,8}$)|((\d{3}-\d{8}|\d{4}-\d{7})|(^1[358]\d{9}|173|176|177\d{8}$))/,
      "errmsg": "请输入正确的手机号码"
    }
  }
  //循环校验表单
  for (var key in formData) {

    var value = formData[key];

    var ruleObj = rules[key];

    //跳过没有设置验证规则的属性
    if (!ruleObj) {
      continue;
    }


    var rule = ruleObj.rule;
    var errmsg = ruleObj["errmsg"];

    //判断是否为默认规则
    if (def_rules[rule]) {
      rule = def_rules[ruleObj.rule].rule;
    }

    if (!errmsg) {
      errmsg = def_rules[ruleObj.rule].errmsg;
    }
    console.log(value, rule);
    if (!rule.test(value)) {
      wx.showModal({
        title: '提示',
        content: errmsg,
        showCancel: false,
        confirmText: "朕知道了"
      })
      result = false;
      break;
    }
  }
  //返回校验结果
  return result;
}

///  调用演示 validForm({ "tel": "1839044333" }, { "tel": { "rule":"183" , errmsg:"请输入正确的号码" } })

/**
 * 对象浅合并
 */
function extend(o, n) {
  for (var p in n) {
    o[p] = n[p];
  }
  return o;
}



/**
 * 用户登录
 */
function userLogin(callBack,pages) {
  
      console.log(2);
      wx.showLoading({
        title: "加载中...",
        mask: true
      });
      wx.authorize({
        "scope": "scope.userInfo",
        success(res) {
          //调用微信登录刷新token
          wx.login({
            success: function(res) {

              wx.request({
                url: getApp().baseUrl + '/wxapi/user/login/' + res.code,
                method: "POST",
                header: {
                  'content-type': 'application/json'
                },
                data: {},
                success: function(res) {

                  if (res.data.status == "200") {
                    try {
                      var userInfo = res.data.mapInfo.userInfo;
                      wx.setStorage({
                        key: "token",
                        data: res.data.mapInfo.token
                      });
                      wx.setStorage({
                        key: "userInfo",
                        data: userInfo
                      });
                      console.log(callBack);
                      if (callBack) {
                        callBack();
                      }
                    } catch (e) {
                      console.error(e);
                      wx.hideLoading()
                    }
                  } else {
                    wx.showToast({
                      title: res.data.info,
                      icon: "none"
                    });
                    wx.hideLoading()
                  }
                  wx.hideLoading()
                },
                //失败处理
                fail: function(res) {
                  wx.showToast({
                    title: "网络请求异常",
                    icon: "none"
                  });
                }
              })
            }
          });
        },
        fail: function(res) {
          var url = '../welcome/welcome'
          if (pages){
            url ='../welcome/welcome?pages=' + pages
         }
          wx.navigateTo({
            url: url
          })
        }
      });
     
   

}




// api地址，请求参数，回调函数，是否遮罩
function request(api, param, callback, mask) {

  //遮罩
  if (mask) {
    wx.showLoading({
      title: "加载中...",
      mask: mask
    });
  }

  wx.getStorage({
    key: 'token',
    success: function(res) {
      wx.request({
        url: getApp().baseUrl + api,
        method: "POST",
        header: {
          'content-type': 'application/json',
          'token': res.data
        },
        data: param,
        success: function(res) {

          if (res.data.status == "200") {
            try {
              if (mask) {
                wx.hideLoading()
              }
              callback(res.data);

            } catch (e) {
              console.error(e);
              if (mask) {
                wx.hideLoading()
              }
            }
          } else {
            wx.showToast({
              title: res.data.info,
              icon: "none"
            });
            if (mask) {
              wx.hideLoading()
            }
          }
          
        },
        //失败处理
        fail: function(res) {
          wx.showToast({
            title: "网络请求异常",
            icon: "none"
          });
        }
      })
    },
    fail: function(e) {
      console.log(e);
    }
  });

}
 




const showToast = (title = '加载中...', icon = 'loading', duration = 60000) => {
  wx.showToast({
    title: title,
    mask: true,
    icon: icon,
    duration: duration
  })
}

const hideToast = () => {
  wx.hideToast()
}

const showModal = (title = '系统提示', str = '', showCancel = true, confirmText = '确定', fn, color = {
  cancelColor: '#999999',
  confirmColor: '#7D73C3'
}, cancelText = "取消") => {
  wx.showModal({
    title: title,
    content: str,
    showCancel: showCancel,
    cancelText: cancelText,
    confirmText: confirmText,
    confirmColor: color.confirmColor,
    cancelColor: color.cancelColor,
    success: res => {
      return typeof fn == 'function' && fn(res)
    }
  })
}

// 用户授权检查
const checkPermission = (type, onSuccess, content) => {
  let that = this
  type = 'scope.' + type;
  wx.getSetting({
    success(getRes) {
      const setting = getRes.authSetting;
      if (setting[type] === false) {
        that.showModal('温馨提示', '请您授权其相关权限', false, '我知道了', res => {
          if (res.confirm) {
            wx.openSetting({
              success(openRes) {
                if (openRes.authSetting[type] === true) {
                  typeof onSuccess === 'function' && onSuccess();
                }
              }
            });
          }
        })
      } else if (setting[type] === true) {
        //如果已有授权直接执行对应动作
        typeof onSuccess === 'function' && onSuccess();
      } else {
        //如果未授权，直接执行对应动作，会自动查询授权
        typeof onSuccess === 'function' && onSuccess();
      }
    }
  })
}




module.exports = {
  uploadImage: uploadImage,
  validForm: validForm,
  extend: extend,
  userLogin: userLogin,
  request: request,
  showToast,
  hideToast,
  showModal,
  checkPermission
}
